package com.yiibai.netty.time.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

	public static void main(String[] args) throws Exception {//原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/netty/netty-time-server.html
		
		String host = null;
		int port = 0;
		
        if (args.length > 1) {
        	host = args[0];
            port = Integer.parseInt(args[0]);
        } else {
        	host = "localhost";
            port = 8080;
        }
		
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			Bootstrap b = new Bootstrap();  // 1.Bootstrap与ServerBootstrap类似，只是它用于非服务器通道，例如客户端或无连接通道。
			b.group(workerGroup);  //2.如果只指定一个EventLoopGroup，它将同时用作boss组和worker组。boss组和worker组不是用于客户端。
			b.channel(NioSocketChannel.class);  // 使用NioSocketChannel来创建客户端通道
			b.option(ChannelOption.SO_KEEPALIVE, true);  // 这里不像我们使用的ServerBootstrap，所以不使用childOption()，因为客户端SocketChannel没有父类
			b.handler(new ChannelInitializer<SocketChannel>() {

				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());
				}
				
			});
			
			ChannelFuture future = b.connect(host, port).sync();
			
			future.channel().closeFuture().sync();
			
		} finally {
			workerGroup.shutdownGracefully();
		}
	}
}
